package io.github.jieblog.juc.day8;

/**
 * jie
 * 2017-06-2017/6/19
 * 死锁
 */
public class DeadLockLearn extends Thread {
    private Object tool;
    private static Object fork1 = new Object();
    private static Object fork2 = new Object();

    public DeadLockLearn(Object tool) {
        this.tool = tool;
        if (tool == fork1) {
            this.setName("哲学家A");
        }

        if (tool == fork2) {
            this.setName("哲学家B");
        }
    }

    @Override
    public void run() {
        if (tool == fork1) {
            synchronized (fork1) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (fork2) {
                    System.out.println("哲学家A吃饭");
                }
            }
        }

        if (tool == fork2) {
            synchronized (fork2) {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (fork1) {
                    System.out.println("哲学家B吃饭");
                }
            }
        }
    }

    public static void main(String[] args) {
        DeadLockLearn deadLockLearn1 = new DeadLockLearn(fork1);
        DeadLockLearn deadLockLearn2 = new DeadLockLearn(fork2);
        deadLockLearn1.start();
        deadLockLearn2.start();
    }
}
